package com.tricky.demo.rabbit.controller;

import cn.hutool.core.lang.UUID;
import cn.hutool.json.JSONUtil;
import com.tricky.demo.rabbit.config.EnumRabbitQueue;
import com.tricky.demo.rabbit.service.TestRabbitService;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping("/test")
@Log4j2
public class RabbitPublisherController {

	@Autowired
	private TestRabbitService testRabbitService;

	@Autowired
	private RabbitTemplate rabbitTemplate;

	/*
	 * @description:消息重复发送，验证消息幂等性，
	 * @author: Kevin,Meng
	 * @date: 2022/11/24 15:46
	 * @param: [msg, id]
	 * @return: java.lang.String
	 **/
	@GetMapping("/sendMsg")
	public String sendMsg(@RequestParam("msg") String msg, @RequestParam("id") String id) {
		MessageProperties messageProperties = new MessageProperties();
		messageProperties.setMessageId(id);
		messageProperties.setContentType("text/plain");
		messageProperties.setContentEncoding("utf-8");
		Message message = new Message(msg.getBytes(), messageProperties);
		log.info("生产消息:" + message.toString());
		// 消息发送确认回调
		CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());
		rabbitTemplate.convertAndSend(EnumRabbitQueue.Demo.getExchange(), EnumRabbitQueue.Demo.getRouteKey(),message,correlationData);
		return correlationData.getId();
	}

	@RequestMapping("/send")
	public String send(@RequestParam("data") String data) {

		testRabbitService.sendData(data);
		Map<String, Object> map = new HashMap<>();
		map.put("data", data);
		return JSONUtil.toJsonStr(map);
	}

	@RequestMapping("/send2")
	public String sendNumber(@RequestParam("number") String data) {
		testRabbitService.sendNumber(data);
		Map<String, Object> map = new HashMap<>();
		map.put("data", data);
		return JSONUtil.toJsonStr(map);
	}
}
